package com.stockz.downloaderx.callback;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.stockz.core.manager.BarManager;
import com.stockz.core.manager.ConfigurationManager;
import com.stockz.core.util.CoreConstant;
import com.stockz.downloaderx.Download;
import com.stockz.downloaderx.Downloader.Callback;
import com.stockz.downloaderx.util.DownloaderConstant;

@Component
public class DatabasePersistenceCallback implements Callback{
	private static Logger logger = Logger.getLogger(DatabasePersistenceCallback.class);
	
	@Autowired
	private BarManager barManager;
	@Autowired
	private ConfigurationManager configurationManager;
	
	public int getOrder() {
		return 900;
	}
	
	public void execute(Download download) {
		logger.trace(this.getClass().getName()+" called");
		if(download != null && download.getDownloadDate() != null
				&& download.getBarList() != null && !download.getBarList().isEmpty()
				&& download.getEvent() != null && EVENT.PARSE.equals(download.getEvent())
				&& download.getType() != null && TYPE.SUCCESS.equals(download.getType())){
			logger.trace("Bar List size to persist : "+download.getBarList().size());
			barManager.persistAll(download.getBarList());
			logger.trace("Successfully persisted Bar List of size "+download.getBarList().size());
			configurationManager.persist(DownloaderConstant.LAST_BSE_BREDTH_DOWNLOAD_DATE,
					CoreConstant.dateFormat.format(download.getDownloadDate()));
			logger.trace("Successfully updated last download date as "+download.getDownloadDate());
		}
	}
}